<?php


namespace app\common\model;


use think\facade\Validate;
use think\Model;

class Room extends Model
{
    public function saveData($data)
    {
        $validate = Validate::make([
            'has_people' => 'elt:count'
        ], [
            'has_people.elt' => '已住人数不能超过可住人数'
        ]);
        if (!$validate->check($data)) {
            exception($validate->getError());
        }
        if (isset($data['id'])) {
            //更新
            $res = $this->where('id', $data['id'])->update($data);
        } else {
            //添加
            Validate::extend('checkUnique', function ($value, $rule) {
                $is_use = $this->where(['title' => $value, 'house_id' => $rule])->find();
                return !$is_use ? true : '宿舍号已被使用';
            });
            $validate1 = Validate::make([
                'title' => 'require|checkUnique:' . $data['house_id']
            ], [
                'title.require' => '宿舍号必填'
            ]);
            if (!$validate1->check($data)) {
                exception($validate1->getError());
            }
            $res = $this->insertGetId($data);
        }
        return $res;
    }

    public function delData($ids)
    {
        if(!is_array($ids)){
            $ids = explode(',',$ids);
        }
        //空宿舍才能删
        $list = $this->where('id', 'in', $ids)->field('id,title,has_people')->select();
        $arr = [];//非空宿舍号
        $ids1 = []; //非空宿舍id
        foreach ($list as $k => $v) {
            if($v['has_people'] != 0){ //非空宿舍
                $arr[] = $v['title'];
                $ids1[] = $v['id'];
            }
        }
        $diff = array_diff($ids,$ids1);
        $res = $this->where('id','in',$diff)->delete();
        if(!empty($arr)){
            exception('宿舍'.implode(',',$arr).'为非空宿舍,无法删除');
        }
        return $res;
    }
}
